package cn.sxw.ld.module.member.service.impl;


import cn.sxw.ld.common.utils.DateUtils;
import cn.sxw.ld.module.member.mapper.DailyRecordMapper;
import cn.sxw.ld.module.member.pojo.*;
import cn.sxw.ld.module.member.service.DailyRecordService;
import cn.sxw.ld.module.member.service.MemberService;
import cn.sxw.ld.module.user.pojo.Employee;
import cn.sxw.ld.module.user.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author: SXW
 * @since: 2025年02月28日 19:54
 * @desc:
 */
@Service
public class DailyRecordServiceImpl extends ServiceImpl<DailyRecordMapper, DailyRecord> implements DailyRecordService {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private MemberService memberService;

    @Override
    public Page getPage(CostPageDto dto) {
        LambdaQueryWrapper<DailyRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(StringUtils.isNoneBlank(dto.getBeginTime()) && StringUtils.isNoneBlank(dto.getEndTime()),
                DailyRecord::getCreateTime, dto.getBeginTime(), dto.getEndTime());
        wrapper.eq(dto.getBsType() != null, DailyRecord::getBsType, dto.getBsType());
        wrapper.like(StringUtils.isNoneBlank(dto.getBsDesc()), DailyRecord::getBsDesc, dto.getBsDesc());
        wrapper.orderByDesc(DailyRecord::getCreateTime);
        Page<DailyRecord> pageInfo = new Page<>(dto.getPage(), dto.getPageSize());
        Page<DailyRecord> page = this.page(pageInfo, wrapper);
        page.getRecords().forEach(dailyRecord -> {
            Long uId = dailyRecord.getCreateUser();
            Employee byId = employeeService.getById(uId);
            dailyRecord.setOperator(byId.getName());
        });
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addRecord(DailyRecord dailyRecord) {
        return this.save(dailyRecord);
    }


    /**
     * 根据统计类型统计数据
     *
     * @param countType 1. 总计
     *                  2. 上周
     *                  3. 上月
     * @return
     */
    @Override
    public Map<String, Integer> getCountData(Integer countType) {
        // 根据类型获得查询结束时间
        List<Date> beginAndEnd = getBeginAndEnd(countType);
        Date begin = beginAndEnd.get(0);
        Date end = beginAndEnd.get(1);
        int memberNum = memberService.getTotalMembers(begin, end);
        BigDecimal totalIncome = baseMapper.getTotal(begin, end, 1);
        BigDecimal totalDisburse = baseMapper.getTotal(begin, end, 2);
        // 查询为空则初始化为0
        if (totalDisburse == null)
            totalDisburse = BigDecimal.ZERO;
        if (totalIncome == null)
            totalIncome = BigDecimal.ZERO;
        HashMap<String, Integer> map = new HashMap<>();
        // 客户新增数量
        map.put("memberNum", memberNum);
        // 收入
        map.put("income", totalIncome.intValue());
        // 支出
        map.put("disburse", totalDisburse.intValue());
        // 盈利
        map.put("profit", totalIncome.subtract(totalDisburse).intValue());
        return map;
    }

    @Override
    public Map<String, Object> getCountChart(int countType) {
        List<Date> beginAndEnd = getBeginAndEnd(countType);
        Date begin = beginAndEnd.get(0);
        Date end = beginAndEnd.get(1);
        // 获取日期、收入、支出、盈利
        List<DailyDataDto> counts = baseMapper.dailyCount(begin, end);
        Map<String, Object> result = new LinkedHashMap<>();
        List<String> dates = new ArrayList<>();
        List<Integer> totalIncome = new ArrayList<>();
        List<Integer> totalExpense = new ArrayList<>();
        List<Integer> newMembers = new ArrayList<>();
        List<Integer> profit = new ArrayList<>();
        // 操作赋值日期和收入、支出、盈利
        counts.forEach(item -> {
            dates.add(item.getDate());
            totalIncome.add(item.getIncome());
            totalExpense.add(item.getExpense());
            profit.add(item.getProfit());
        });
        // 新增会员数
        List<DailyDataDto> memberCount = memberService.getDailyData(end, begin);
        memberCount.forEach(item -> {
            newMembers.add(item.getMembers());
        });
        result.put("dates", dates);
        result.put("totalIncome", totalIncome);
        result.put("totalExpense", totalExpense);
        result.put("newMembers", newMembers);
        result.put("profit", profit);
        return result;
    }

    /**
     * 处理开始结束时间
     *
     * @param bsType
     * @return
     */
    private List<Date> getBeginAndEnd(int bsType) {
        ArrayList<Date> dates = new ArrayList<>();
        switch (bsType) {
            case 1: // 总计
                dates.add(null);
                dates.add(null);
                break;
            case 2: // 查上周
                Date[] lastLastWeekRange = DateUtils.getLastLastWeekRange();
                dates.add(lastLastWeekRange[0]);
                dates.add(lastLastWeekRange[1]);
                break;
            case 3: // 查上个月
                Date[] lastLastMonthRange = DateUtils.getLastMonthRange();
                dates.add(lastLastMonthRange[0]);
                dates.add(lastLastMonthRange[1]);
                break;
            default:
                dates.add(null);
                dates.add(null);
                break;
        }
        return dates;

    }
}
